package com.handu.luna.core.domain.user;

import javax.persistence.Entity;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Size;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import com.handu.luna.core.domain.BasePersistentDomain;
import com.handu.luna.core.domain.BossException;

@Entity
public class UserRank extends BasePersistentDomain<UserRankRepository> {
	
	public UserRank(){};
	
	public UserRank(String rankName, long minRank, long maxRank, boolean isSpecial) {
		super();
		this.rankName = rankName;
		this.minRank = minRank;
		this.maxRank = maxRank;
		this.isSpecial = isSpecial;
	}
	
	public UserRank(String rankName, long minRank, long maxRank, boolean isSpecial,long goodsSale,boolean isRankPrice) {
		super();
		this.rankName = rankName;
		this.minRank = minRank;
		this.maxRank = maxRank;
		this.isSpecial = isSpecial;
		this.isRankPrice = isRankPrice;
		this.goodsSale = goodsSale;
	}
	@Size(min=1,max=50, message="等级名称不能为空.")
	private String rankName;
	
	@Min(value=1, message="积分下限不能为空且不能小于1.")
	@Max(value=9999999, message="积分下限不能大于最大值9999999.")
	private long minRank;
	
	@Min(value=1, message="积分上限必须为数字且不能小于1.")
	@Max(value=9999999, message="积分不能大于最大值9999999.")
	private long maxRank;
	
	@Min(value=0, message="积分上限必须为数字且不能小于1.")
	@Max(value=100, message="积分不能大于最大值9999999.")
	private long goodsSale;//商品折扣
	
	private boolean isRankPrice;//是否显示会员价格
	
	private boolean isSpecial;
	
	public void validate(String objectName,BindingResult bindingResult){
		if(maxRank<minRank){
			bindingResult.addError(new FieldError(objectName,"maxRank","积分上限不能小于积分下限"));
		}
		if(this.getId() == null)this.setId(0L);
		if(this.getRankName()!=null 
				&& this.getRepository().findRankNameExist(this.getRankName().trim(),this.getId()).size()>0){
			bindingResult.addError(new FieldError(objectName,"rankName",this.getRankName().trim(),false,new String[0],new String[0],"等级名称不能重复"));
		}
	}
	
	public void validateBeforeDelete(){
		if(context.getUserRepository().has("userRank", this.getId())){
			throw new BossException("这个用户级别下存在用户，不允许删除。");
		}		
	}
	
	public long getGoodsSale() {
		return goodsSale;
	}

	public void setGoodsSale(long goodsSale) {
		this.goodsSale = goodsSale;
	}

	public String getRankName() {
		return rankName;
	}
	public void setRankName(String rankName) {
		this.rankName = rankName;
	}
	public long getMinRank() {
		return minRank;
	}
	public void setMinRank(long minRank) {
		this.minRank = minRank;
	}
	public long getMaxRank() {
		return maxRank;
	}
	public void setMaxRank(long maxRank) {
		this.maxRank = maxRank;
	}
	public boolean getIsSpecial() {
		return isSpecial;
	}
	public void setIsSpecial(boolean isSpecial) {
		this.isSpecial = isSpecial;
	}
	public boolean getIsRankPrice() {
		return isRankPrice;
	}
	public void setIsRankPrice(boolean isRankPrice) {
		this.isRankPrice = isRankPrice;
	}
	
	
}
